package com.ziyueyuwen.xiniao.controller.subscription;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.LogUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.service.SubscriptionService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.taobao.api.Constants.CONTENT_TYPE_JSON;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveErrorMsgAndData;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveSuccessMsgAndData;
import static com.ziyueyuwen.xiniao.util.ConstUtil.DEFAULT_ENCODE;
import static com.ziyueyuwen.xiniao.util.ConstUtil.SUCCESS_JSON_STR;

/**
 * @author jun 2018/12/26.
 */
@Controller
@RequestMapping("/subscription")
public class SubscriptionController {

    @Autowired
    private SubscriptionService subscriptionService;

    @RequestMapping(value = "/notify.do", method = RequestMethod.POST)
    public void subscription(HttpServletRequest request,
                             HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("消息订阅");
        try {
            // do.
            String eeoNotifyStr = IOUtils.toString(request.getInputStream(), DEFAULT_ENCODE);
            LogUtil.info("eeoNotifyStr: {}", eeoNotifyStr);
            subscriptionService.readData(eeoNotifyStr);
            JSONObject retObj = JSON.parseObject(SUCCESS_JSON_STR);
            // result
            saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            writeResResult(hrc.getResult(), response);
        }
    }

    private void writeResResult(JSONObject object, HttpServletResponse response) {
        try {
            if (response == null) {
                throw new IllegalArgumentException("parameter error.");
            }
            response.setContentType(CONTENT_TYPE_JSON);
            response.setCharacterEncoding(DEFAULT_ENCODE);
            PrintWriter pw = response.getWriter();
            pw.write(object.toJSONString());
            pw.close();
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
